package indexes;

import java.io.IOException;

import trees.AVLTree;
import util.PlayerLogger;

/**
 * A player index relates a player's alphanumeric id to
 * a file offset.
 * @author bfults (Brian Fults - 905084698)
 *
 */
public class PlayerIDIndex
{
    private AVLTree<PlayerID> index;
    
    /**
     * Default constructor.  Trees may be created with a logger.
     * @param logger may be null.
     */
    public PlayerIDIndex(PlayerLogger logger)
    {
        index = new AVLTree<PlayerID>(logger);
    }   
 
    /**
     * Adds the player id and the offset to the indexing structure.
     * @param playerId an alphanumeric id
     * @param offset the file offset for this player's record.
     */
    public void add( String playerId, Long offset)
    {
        index.insert(new PlayerID(playerId, offset));
    }
 
    /**
     * Attempts to locate the player within the index based
     * on the player id.  Creates a player id with impossibly negative
     * offset.  If the player is found, we will get back an object
     * with the correct offset, otherwise we will get null.
     * @param key alphanumeric id to search for.
     * @return the offset for the give key, or null if the player
     * isn't found.
     * @throws IOException 
     */
    public Long get( String key ) throws IOException
    {
        PlayerID found = index.find(new PlayerID(key, -999));
        return found != null ? found.getOffset() : null;
    }
    
    /**
     * Removes the record belonging to this
     * alphanumeric key from the indexing structure.
     * The keys are unique, so we know it's ok to send
     * a negative offset and let compareTo tell the tree
     * they are equal.
     * @param key
     */
    public void remove(String key)
    {
        index.remove(new PlayerID(key, -999));
    }
    
    /**
     * Requests that the tree log its structure.
     * @throws IOException
     */
    public void logIndex() throws IOException
    {
        index.logTree();
    }

}
